﻿<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>原生JS表格列表全选反选代码 - 站长素材</title>

<style>
* {
	padding:0;
	margin:0;
}
.wrap {
	width:300px;
	margin:20px auto 0;
}
table {
	border-collapse:collapse;
	border-spacing:0;
	border:1px solid #c0c0c0;
	width:300px;
}
th,td {
	border:1px solid #d0d0d0;
	color:#404060;
	padding:10px;
}
th {
	background-color:#09c;
	font:bold 16px "微软雅黑";
	color:#fff;
}
td {
	font:14px "微软雅黑";
}
tbody tr {
	background-color:#f0f0f0;
}
tbody tr:hover {
	cursor:pointer;
	background-color:#fafafa;
}
</style>
</head>
<body>
<div class="wrap">
    <table>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" id="j_cbAll" />
                </th>
                <th>菜名</th>
                <th>饭店</th>
            </tr>
        </thead>
        <tbody id="j_tb">
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>红烧肉</td>
                <td>家里蹲</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>西红柿鸡蛋</td>
                <td>家里蹲</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>红烧狮子头</td>
                <td>家里蹲</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>日式肥牛</td>
                <td>家里蹲</td>
            </tr>

        </tbody>
    </table>
</div>

<script>
 var all = document.getElementById("j_cbAll");
 var tbody = document.getElementById("j_tb");
 var checkboxs = tbody.getElementsByTagName("input");
 all.onclick = function() {
     for (var i = 0; i < checkboxs.length; i++) {
         var checkbox = checkboxs[i];
         checkbox.checked = this.checked;
     }
 };
 for (var i = 0; i < checkboxs.length; i++) {
     checkboxs[i].onclick = function() {
         var isCheckedAll = true;
         for (var i = 0; i < checkboxs.length; i++) {
             if (!checkboxs[i].checked) {
                 isCheckedAll = false;
                 break;
             }
         }
         all.checked = isCheckedAll;
     };
 }
 </script>
 
<div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';">
<p>适用浏览器：IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗.</p>
<p>来源：<a href="http://sc.chinaz.com/" target="_blank">站长素材</a></p>
</div>
</body>
</html>

